﻿

// Write a program that finds the largest area of equal neighbor elements in a rectangular matrix and prints its size.
// Breadth-first search algorithm

using System;

class BFS
{
    static void Main()
    {
        int[,] matrix =
        {
            { 1, 3, 2, 2, 2, 4 },
            { 3, 3, 3, 2, 4, 4 },
            { 4, 3, 1, 2, 3, 3 },
            { 4, 3, 1, 3, 3, 1 },
            { 4, 3, 3, 3, 1, 1 }
        };

        int rowsCount = matrix.GetLength(0);
        int colsCount = matrix.GetLength(1);

        bool[,] counted = new bool[rowsCount, colsCount];

        int largestArea = 0;
        for (int rows = 0; rows < rowsCount; rows++)
        {
            for (int cols = 0; cols < colsCount; cols++)
            {
                if (!counted[rows, cols])
                {
                    int currentArea = CalculateArea(matrix, counted, rows, cols);

                    if (currentArea > largestArea)
                    {
                        largestArea = currentArea;
                    }
                }
            }
        }

        Console.WriteLine(largestArea);
    }

    private static int CalculateArea(int[,] matrix, bool[,] counted, int rows, int cols)
    {
        int currentArea = 1;
        counted[rows, cols] = true;

        for (int r = rows - 1; r <= rows + 1; r++)
        {
            for (int c = cols - 1; c <= cols + 1; c++)
            {
                if (r >= 0 && r < matrix.GetLength(0) && c >= 0 && c < matrix.GetLength(1))
                {
                    if (!counted[r, c])
                    {
                        if (matrix[r, c] == matrix[rows, cols])
                        {
                            currentArea += CalculateArea(matrix, counted, r, c);
                        }
                    }
                }
            }
        }

        return currentArea;
    }
}
